import urllib, urllib2, re
import mc
                
###################################
########  Class SC2Casts  #########
###################################
                                      
class SC2Casts: 

        USERAGENT = "Mozilla/5.0 (Windows; U; Windows NT 6.1; en-GB; rv:1.9.2.8) Gecko/20100722 Firefox/3.6.8"
        
        def __init__(self):
            itemList = mc.ListItems()
                
            
        def action(self, params):
                print 'testaction action-> ' + params['action']
                get = params.get
                if (get("action") == "rootTop"):
                        self.rootTop()
                if (get("action") == "rootBrowse"):
                        self.rootBrowse()
                if (get("action") == "browseEvents"):
                        self.browseEvents(params)
                if (get("action") == "browseMatchups"):
                        self.browseMatchups()
                if (get("action") == "browseCasters"):
                        self.browseCasters(params)
                if (get("action") == "showTitles" or get("action") == "showTitlesTop" or get("action") == "showTitlesSearch"):
                        self.showTitles(params)
                if (get("action") == "showGames"):
                        self.showGames(params)
        
        # ------------------------------------- Menu functions ------------------------------------- #
        
        # display the root menu
        def root(self):
                print 'testRoot'
                self.itemList = mc.ListItems()
                
                self.addCategory('recent casts', 'http://sc2casts.com/index.php', 'showTitles')
                self.addCategory("top casts", '', 'rootTop')
                self.addCategory("browse casts", '', 'rootBrowse')
                self.addCategory("search casts", '', 'showTitlesSearch')
                
                mc.GetActiveWindow().GetList(120).SetItems(self.itemList)
    
        # display the top casts menu
        def rootTop(self):
                self.itemList = mc.ListItems()
                self.addCategory("top 24h", 'http://sc2casts.com/top/index.php', 'showTitlesTop')
                self.addCategory("top week", 'http://sc2casts.com/top/index.php?week', 'showTitlesTop')
                self.addCategory("top month", 'http://sc2casts.com/top/index.php?month', 'showTitlesTop')
                self.addCategory("top all time", 'http://sc2casts.com/top/index.php?all', 'showTitlesTop')
                mc.GetActiveWindow().GetList(120).SetItems(self.itemList)
                        
        # display the browse casts menu
        def rootBrowse(self):
                self.itemList = mc.ListItems()
                self.addCategory("browse events", 'http://sc2casts.com/browse/index.php', 'browseEvents')
                self.addCategory("browse matchups", '', 'browseMatchups')
                self.addCategory("browse casters", 'http://sc2casts.com/browse/index.php', 'browseCasters')
                mc.GetActiveWindow().GetList(120).SetItems(self.itemList)
        # display the browse events menu
        def browseEvents(self, params = {}):
                get = params.get
                link = self.getRequest(get("url"))
                event = re.compile('<a href="/event(.*?)">(.*?)</a>').findall(link)

                self.itemList = mc.ListItems()
                for i in range(len(event)):
                        self.addCategory(event[i][1], 'http://sc2casts.com/event'+event[i][0], 'showTitles')
                mc.GetActiveWindow().GetList(120).SetItems(self.itemList)
        # display the browse casters menu
        def browseMatchups(self):
                self.itemList = mc.ListItems()
                self.addCategory('PvZ', 'http://sc2casts.com/matchups-PvZ', 'showTitles')
                self.addCategory('PvT', 'http://sc2casts.com/matchups-PvT', 'showTitles')
                self.addCategory('TvZ', 'http://sc2casts.com/matchups-TvZ', 'showTitles')
                self.addCategory('PvP', 'http://sc2casts.com/matchups-PvP', 'showTitles')
                self.addCategory('TvT', 'http://sc2casts.com/matchups-TvT', 'showTitles')
                self.addCategory('ZvZ', 'http://sc2casts.com/matchups-ZvZ', 'showTitles')
                mc.GetActiveWindow().GetList(120).SetItems(self.itemList)
                
        # display the browse casters menu
        def browseCasters(self, params = {}):
                get = params.get
                link = self.getRequest(get("url"))
                caster = re.compile('<a href="/caster(.*?)">(.*?)</a>').findall(link)

                self.itemList = mc.ListItems()
                for i in range(len(caster)):
                        self.addCategory(caster[i][1], 'http://sc2casts.com/caster'+caster[i][0], 'showTitles', len(caster))
                mc.GetActiveWindow().GetList(120).SetItems(self.itemList)
                
        # ------------------------------------- Add functions ------------------------------------- #

        
        def addCategory(self,title,url,action, count = 0):
                print 'testaddCategory url->' + url
                
                #listitem=xbmcgui.ListItem(title, iconImage="DefaultFolder.png", thumbnailImage="DefaultFolder.png")
                #listitem.setInfo( type="Video", infoLabels={ "Title": title } )
                #xbmcplugin.addDirectoryItem(handle=int(sys.argv[1]), url=url, listitem=listitem, isFolder=True, totalItems=count)
                
                item = mc.ListItem( mc.ListItem.MEDIA_VIDEO_CLIP )
                item.SetLabel(title)
                #item.SetPath("http://www.youtube.com/watch?v=oHg5SJYRHA0")
                #item.SetContentType("text/html")
                #item.SetThumbnail("DefaultFolder.png"")
                # I don't know where that file is
                
                item.SetProperty("url", url)
                item.SetProperty("action", action)
                item.SetProperty("title", title)
                
                self.itemList.append(item);
    
        def addVideo(self,title,url):
                # Check if URL is a 'fillUp' URL
                if url != 'fillUp':
                        url = self.getVideoUrl(url)

                print 'addVideo url ->' + url
                
                item = mc.ListItem( mc.ListItem.MEDIA_VIDEO_CLIP )
                item.SetLabel(title)
                item.SetPath(url)
                item.SetContentType("text/html")
                #item.SetThumbnail("DefaultVideo.png"")
                # I don't know where that file is
                item.SetProperty("url", url)
                item.SetProperty("action", 'playVideo')
                
                self.itemList.append(item);
                
        # ------------------------------------- Show functions ------------------------------------- #
        
        
        def showTitles(self, params = {}):
                get = params.get
                url = get("url")
                
                # Check if user want to search
                if get("action") == 'showTitlesSearch':
                        text = mc.ShowDialogKeyboard("Search", "", False)
                        print "miketest1" + text
                        url = 'http://sc2casts.com/?q='+text
            
                url = urllib.unquote(url)              
                print 'url -> ' + url  
                
                link = self.getRequest(url)
                
                # Get settings
                #boolMatchup = self.__settings__.getSetting( "matchup" )
                #boolNr_games = self.__settings__.getSetting( "nr_games" )
                #boolEvent = self.__settings__.getSetting( "event" )
                #boolRound = self.__settings__.getSetting( "round" )
                #boolCaster = self.__settings__.getSetting( "caster" )
                
                boolMatchup = 'true'
                boolNr_games = 'true'
                boolEvent = 'true'
                boolRound = 'true'
                boolCaster = 'true'
                
                # Get info to show
                print 'regexing page: ' + get("action") 
                
                caster = re.compile('<a href="/.+?"><span class="caster_name">(.*?)</span></a>').findall(link)
                matchup = re.compile('<span style="color:#cccccc">(.*?)</span>').findall(link)
                roundname = re.compile('<span class="round_name">(.*?)</span>').findall(link)
                checkSource = re.compile('title="on (.*?)"').findall(link)
                event = re.compile('<span class="event_name".*?>(.*?)</span>').findall(link)

                #Different source if URL is .../top
                print 'regexing title'
                if get("action") == 'showTitlesTop':
                        title = re.compile('<h3><a href="(.+?)"><b >(.+?)</b> vs <b >(.+?)</b>&nbsp;\((.*?)\)</a></h3>').findall(link)
                else:
                        title = re.compile('<h2><a href="(.+?)"><b >(.+?)</b> vs <b >(.+?)</b> \((.*?)\)</a>').findall(link)

                print 'populating list'
                self.itemList = mc.ListItems()
                for i in range(len(event)):
                        if checkSource[i] != 'YouTube':
                                pass
                        else:
                                desc = ''
                                if boolMatchup == 'true':
                                        desc += matchup[i] + ' | '

                                desc += title[i][1] + ' vs ' + title[i][2] + ' | '
                                        
                                if boolNr_games == 'true':
                                        desc += title[i][3] + ' | '
                                if boolEvent == 'true':
                                        desc += event[i] + ' | '
                                if boolRound == 'true':
                                        desc += roundname[i] + ' | '
                                if boolCaster == 'true':
                                        desc += 'cast by: ' + caster[i]
                                
                                self.addCategory(desc,title[i][0],'showGames')
                
                mc.GetActiveWindow().GetList(120).SetItems(self.itemList)
#                for i in range(len(event)):        
#                    print title[i][0]
#                    print matchup[i]
#                    print title[i][1] + ' vs ' + title[i][2]
#                    print event[i]
#                    print roundname[i]
#                    print caster[i]
#                    print checkSource[i]
#                    print '---'
                    
        def showGames(self, params = {}):
                print 'showGames'
                get = params.get
                link = self.getRequest('http://sc2casts.com'+get("url"))
                matchCount = re.compile('<div id="g(.+?)"(.+?)</div></div>').findall(link)
                self.itemList = mc.ListItems()
                if len(matchCount) > 0:
                        for i in range(len(matchCount)):
                                #videoContent=re.compile('<param name="movie" value="http://www.youtube.com/v/(.+?)\?.+?"></param>').findall(matchCount[i][1])
                                videoContent=re.compile('src="https://www.youtube.com/embed/(.+?)"').findall(matchCount[i][1])
                                if len(videoContent) == 0:
                                        self.addVideo('Game '+ str(i+1), 'fillUp')
                                if len(videoContent) == 1:
                                        self.addVideo('Game '+ str(i+1), videoContent[0])
                                if len(videoContent) > 1:
                                        for k in range(len(videoContent)):
                                                self.addVideo('Game '+ str(i+1)+', part '+ str(k+1), videoContent[k])
                else:
                        videoContent=re.compile('src="https://www.youtube.com/embed/(.+?)"').findall(link)
                        if len(videoContent) > 1:
                                for n in range(len(videoContent)):
                                        self.addVideo('Game 1, part '+ str(n+1), videoContent[n])
                        else:
                                self.addVideo('Game 1', videoContent[0])
                mc.GetActiveWindow().GetList(120).SetItems(self.itemList)
                        
        # ------------------------------------- Data functions ------------------------------------- #

        
#        def getParams(self, paramList): 
#                splitParams = paramList[paramList.find('?')+1:].split('&')
#                paramsFinal = {}
#                for value in splitParams:
#                        splitParams = value.split('=')
#                        type = splitParams[0]
#                        content = splitParams[1]
#                        if type == 'url':
#                                content = urllib.unquote_plus(content)
#                        paramsFinal[type] = content
#                return paramsFinal
                
        def getRequest(self, url):
                req = urllib2.Request(url)
                req.add_header('User-Agent', self.USERAGENT)
                response = urllib2.urlopen(req)
                link=response.read()
                response.close()
                return link
        
        def getVideoUrl(self, url):
                print 'getVideoUrl - > ' + url
                return 'https://www.youtube.com/embed/' + url
            
                link = self.getRequest('http://www.youtube.com/watch?v='+url+'&safeSearch=none&hl=en_us')
                fmtSource = re.findall('"url_encoded_fmt_stream_map": "([^"]+)"', link)
                fmt_url_map = urllib.unquote_plus(fmtSource[0]).split(',url=')
                links = {}
                        
                for fmt_url in fmt_url_map:
                                url = fmt_url.replace('\u0026','&')
                                quality = url[url.rfind('&itag=')+6:]
                                if(url.find('&itag=')!=url.rfind('&itag=')):
                                                url = url[:url.rfind('&itag=')]
                                if (url.rfind('; codecs')>0):
                                                url = url[:url.rfind('; codecs')]
                                links[int(quality)] = url
                
                #hd_quality = int(self.__settings__.getSetting( "hd_videos" ))
                hd_quality = 1
                get = links.get
                
                # Select SD quality, standard
                if (get(35)):
                        url = get(35)
                elif (get(34)):
                        url = get(34)
                
                # Select HD quality if wanted
                if (hd_quality > 0): # <-- 720p
                        if (get(22)):
                                url = get(22)
                if (hd_quality > 1): # <-- 1080p
                        if (get(37)):
                                url = get(37)
                                
                return url
                